package com.fone.player.storage;

import java.io.File;
import java.util.ArrayList;
import java.util.Locale;

import android.content.Context;
import android.database.Cursor;
import android.os.Environment;
import android.os.Message;
import android.provider.MediaStore;

import com.fone.player.R;
import com.fone.player.entity.MediaFile;
import com.fone.player.entity.MediaFolder;
import com.fone.player.util.L;

import de.greenrobot.event.EventBus;

/**
 * 
 * 文件夹扫描,读取媒体库中的文件,把文件归类到相应文件夹
 * 
 * @author wangyang
 * @since 2014年4月23日
 */
public class FileFastScanRunnable implements Runnable {
	public static final String TAG = FileFastScanRunnable.class.getSimpleName();
	private Context mContext = null;
	// 文件集合
	private ArrayList<MediaFile> mMediaFileList = new ArrayList<MediaFile>();
	// 文件夹和文件集合
	private ArrayList<MediaFolder> mMediaFolderList = new ArrayList<MediaFolder>();
	private boolean mIsStop = false;
	private long mTotalFileNum = 0;
	private long mMediaFileNum = 0;

	FileFastScanRunnable(Context context) {
		mContext = context;
	}

	@Override
	public void run() {
		synchronized (TAG) {
			try {

				// 扫描开始
				Message message = new Message();
				message.what = StorageModule.MSG_ACTION_SCANNER_STARTED;
				EventBus.getDefault().post(message);

				getVideoFolderListByMediaStore();

				// 扫描完成
				if (mMediaFolderList.size() != 0) {

					// 过滤空文件夹
					for (MediaFolder mediaFolder : mMediaFolderList) {
						if (mediaFolder.getMediaFolderTotalNum() == 0) {
							mMediaFolderList.remove(mediaFolder);
						}
					}

					// 入库
					FileDataBaseAdapter.getInstance().addFolderList(
							mMediaFolderList, mMediaFileList);

					// 通知
					message.what = StorageModule.MSG_ACTION_SCANNER_FINISHED;
					EventBus.getDefault().post(message);

				} else {
					L.e(TAG, "run", "not find any media file in sdcard!");
				}

			} catch (Throwable e) {
				e.printStackTrace();
			}
		}
	}

	public void cancel() {
		mIsStop = true;
	}

	/**
	 * 
	 * 将视频归类到文件夹
	 * 
	 * @return ArrayList<MediaFolder> 视频文件夹集合
	 */
	public void getVideoFolderListByMediaStore() {
		// MediaStore.Video.Media.DATA：视频文件路径；
		// MediaStore.Video.Media.DISPLAY_NAME : 视频文件名，如 testVideo.mp4
		// MediaStore.Video.Media.TITLE: 视频标题 : testVideo

		Cursor cursor = mContext.getContentResolver().query(
				MediaStore.Video.Media.EXTERNAL_CONTENT_URI, null, null, null,
				null);

		if (cursor == null) {
			L.e(TAG, "scanAllVideoFilesFormDB", "cursor == null");
			return;
		}

		L.v(TAG, "getVideoFolderListByMediaStore",
				"cursor.count:" + cursor.getCount() + " StorageState: "
						+ Environment.getExternalStorageState());

		while (cursor.moveToNext()) {

			if (mIsStop) {
				// 停止
				Message message = new Message();
				message.what = StorageModule.MSG_ACTION_SCANNER_STOPPED;
				EventBus.getDefault().post(message);
				return;
			}

			String url = cursor.getString(cursor
					.getColumnIndexOrThrow(MediaStore.Video.Media.DATA));

			File file = new File(url);
			if (!file.exists()) {
				L.e(TAG, "getVideoFolderListByMediaStore", url + " no exists!");
				continue;
			}

			mTotalFileNum++;

			// 读取文件信息
			MediaFile mediaFile = getMediaFileByCursor(cursor);
			if (mediaFile == null) {
				continue;
			}

			mMediaFileNum++;

			int postion = isContainsPath(mMediaFolderList, file.getParent());
			if (postion == -1) {

				MediaFolder folder = new MediaFolder();
				folder.setMediaFolderPath(file.getParent());

				File parentFile = file.getParentFile();
				if (parentFile != null) {
					String parentFilePath = parentFile.getParent();
					folder.setMediaFolderParentPath(parentFilePath);
					if (!"".equals(parentFilePath)) {
						folder.setMediaFolderName(parentFile
								.getPath()
								.substring(
										parentFile.getPath().lastIndexOf("/") + 1));
					}

				}

				mMediaFileList.add(mediaFile);
				folder.addMediaFile(mediaFile);
				mMediaFolderList.add(folder);

			} else {

				MediaFolder folder = (MediaFolder) mMediaFolderList
						.get(postion);

				folder.addMediaFile(mediaFile);

				mMediaFileList.add(mediaFile);
				mMediaFolderList.set(postion, folder);

			}
			// 发送进度
			sendProcessingMessage(mMediaFileNum, mTotalFileNum);
		}

		if (cursor != null) {
			cursor.close();
		}

	}

	/**
	 * 
	 * 发送进度信息
	 * 
	 * @param mediaFileNum
	 *            符合要求的文件数
	 * @param totalFileNum
	 *            已搜索到的文件数
	 * @return void
	 */
	private void sendProcessingMessage(long mediaFileNum, long totalFileNum) {
		Message message = new Message();
		message.what = StorageModule.MSG_ACTION_SCANNER_PROCESSING;
		StringBuffer stringBuffer = new StringBuffer(mContext.getResources()
				.getString(R.string.search_mdeia_msg))
				.append(mediaFileNum)
				.append(File.separator)
				.append(totalFileNum)
				.append(mContext.getResources().getString(
						R.string.search_cancel_msg));
		L.v(TAG, stringBuffer.toString());
		message.obj = stringBuffer.toString();
		EventBus.getDefault().post(message);
	}

	/**
	 * 
	 * 根据游标读取媒体文件对象
	 * 
	 * @param cursor
	 *            游标
	 * @return MediaFile 媒体文件对象
	 */
	private MediaFile getMediaFileByCursor(Cursor cursor) {
		String filePath = cursor.getString(cursor
				.getColumnIndex(MediaStore.Video.Media.DATA));
		File file = new File(filePath);
		String fileName = file.getName();
		int dotIndex = fileName.lastIndexOf(".");
		if (dotIndex == -1) {
			return null;
		}
		String extension = fileName.substring(dotIndex + 1).toLowerCase(
				Locale.getDefault());

		// 非自拍视频进行文件大小过滤,自拍视频忽略大小比对
		if (!file.getParent().toLowerCase(Locale.getDefault())
				.contains(StorageConfig.SYSTEM_AUTODYNE_VIDEO_PATH)
				&& !file.getParent().toLowerCase(Locale.getDefault())
						.contains(StorageConfig.FONE_AUTODYNE_VIDEO_PATH)) {

			// 过滤文件大小,1M以下的视频忽略
			if (file.length() < StorageConfig.FILE_SIZE_FILTER_CONDITION) {
				return null;
			}

		}

		// 匹配视频
		if (!StorageConfig.matchVideoFile(extension)) {
			return null;
		}

		MediaFile mediaFile = new MediaFile();

		String data = cursor.getString(cursor
				.getColumnIndex(MediaStore.Video.Media.DATA));
		mediaFile.setMediaFilePath(data);
		mediaFile.setMediaFileParentPath(file.getParent());
		String title = cursor.getString(cursor
				.getColumnIndex(MediaStore.Video.Media.TITLE));
		mediaFile.setMediaFileName(title);
		String displayName = cursor.getString(cursor
				.getColumnIndex(MediaStore.Video.Media.DISPLAY_NAME));
		mediaFile.setMediaFileNameSuffix(displayName);
		long size = cursor.getLong(cursor
				.getColumnIndex(MediaStore.Video.Media.SIZE));
		mediaFile.setMediaFileSize(size);
		String album = cursor.getString(cursor
				.getColumnIndex(MediaStore.Video.Media.ALBUM));
		mediaFile.setMediaFileAlbumName(album);
		String artist = cursor.getString(cursor
				.getColumnIndex(MediaStore.Video.Media.ARTIST));
		mediaFile.setMediaFileArtistName(artist);
		long dateModified = cursor.getLong(cursor
				.getColumnIndex(MediaStore.Video.Media.DATE_MODIFIED));
		mediaFile.setMediaFileDateModified(dateModified);
		long duration = cursor.getLong(cursor
				.getColumnIndex(MediaStore.Video.Media.DURATION));
		mediaFile.setMediaFileDateDuration(duration);
		return mediaFile;
	}

	/**
	 * 
	 * 判断路径是否在当前集合中重复
	 * 
	 * @param mediaFolderList
	 *            路径集合
	 * @param parentPath
	 *            比对的路径
	 * @return int 重复路径的索引,否则返回-1
	 */
	public int isContainsPath(ArrayList<MediaFolder> mediaFolderList,
			String path) {

		if (mediaFolderList == null) {
			L.w(TAG, "isPathInArray", "mediaFolderList is null");
			return -1;
		}

		if (mediaFolderList.size() == 0) {
			L.w(TAG, "isPathInArray", "mediaFolderList.size()=0");
			return -1;
		}
		int index = 0;
		for (MediaFolder mediaFolder : mediaFolderList) {
			if (mediaFolder.getMediaFolderPath().equals(path)) {
				return index;
			}
			index++;
		}

		return -1;
	}

}
